import { Dialog } from '@/utils/model'
import Vue from 'vue'
import store from '@/vuex/store'
let dialog = null

export function globalAlert({ vm, type, msg, eventConfig = () => {} }) {
  let config = null
  try {
    config = require(`@/components/globalAlertTemplate/${type}/config.js`).default
  } catch (ex) {
    console.log(ex)
  }
  // 定义传参
  const props = {
    msg
  }

  // 定义回调事件
  const events = {
    cancel: () => {
      eventConfig()
      vm.$store.dispatch('dialogManager/closeDialog', dialog.key)
      vm.$store.dispatch('dialogManager/removeDialog', dialog.key)
    }
  }
  // 定义弹窗配置
  const meta = {
    size: config && config.size ? config.size : 'small',
    closeOnClickModal: false,
    isShowFooter: false,
    dialogType: config && config.dialogType ? config.dialogType : 'globalAlert',
    globalAlertConfig: config,
    showClose: config ? config.showClose : undefined,
    bodyHeight: config ? config.bodyHeight : undefined
  }
  // 引入弹窗主体组件
  let component = null
  try {
    component = require(`@/components/globalAlertTemplate/${type}/index.vue`).default
  } catch (ex) {
  }
  if (component) {
    if (dialog) {
      // 若弹窗存在
      // 设置需要改动的传值
      dialog.props = props
      dialog.meta = meta
      dialog.component = component
      vm.$store.dispatch('dialogManager/updateDialog', dialog)
    } else {
      // 新建并添加弹窗
      dialog = new Dialog(component, props, events, meta)
      vm.$store.dispatch('dialogManager/addDialog', dialog)
    }
    vm.$store.dispatch('dialogManager/openDialog', dialog.key)
  }
  return dialog
}

export function globalAlterWithoutVm({ type, msg }) {
  const vm = new Vue({
    store
  })
  globalAlert({ vm, type, msg })
  setTimeout(() => {
    vm.$destroy()
  })
}
